export const getDateDiff = (dateTimeStamp) => {
  var minute = 1000 * 60
  var hour = minute * 60
  var day = hour * 24
  // var halfamonth = day * 15
  var month = day * 30

  var now = new Date().getTime()
  var diffValue = now - dateTimeStamp * 1000

  if (diffValue < 0) {
    return
  }
  var monthC = diffValue / month
  var weekC = diffValue / (7 * day)
  var dayC = diffValue / day
  var hourC = diffValue / hour
  var minC = diffValue / minute
  let result = ''
  if (monthC >= 1) {
    result = '' + parseInt(monthC) + '月前'
  } else if (weekC >= 1) {
    result = '' + parseInt(weekC) + '周前'
  } else if (dayC >= 1) {
    result = '' + parseInt(dayC) + '天前'
  } else if (hourC >= 1) {
    result = '' + parseInt(hourC) + '小时前'
  } else if (minC >= 1) {
    result = '' + parseInt(minC) + '分钟前'
  } else {
    result = '刚刚'
  }

  return result
}

export const isAndroid = () => {
  const u = navigator.userAgent
  return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
}

export const isIOS = () => {
  const u = navigator.userAgent
  console.log(u)
  return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
}

/**
 * 格式化剩余时间
 * @param {*} endtime
 * @param {*} splitChar[] (e.g. ['秒', '分', '小时', '天'])
 */
export const formatRestTime = (endtime, splitChar = []) => {
  var time = (parseInt(endtime) - new Date().getTime()) / 1000
  return formatRestFixedTime(time, splitChar)
}

export const formatRestFixedTime = (time, splitChar = []) => {
  var duration = formatCountDownTime(time)
  if (duration.length) {
    if (splitChar.length) {
      let text = ''
      for (let i = 0; i < duration.length; i++) {
        text = duration.pop() + splitChar[i] + text
      }
      return text
    }
    return duration.join(':')
  }
  return '结束'
}

export const formatCountDownTime = (time) => {
  var duration = []
  if (time > 0) {
    let day = Math.floor(time / 60 / 60 / 24)
    if (day > 0) {
      duration.push(day)
    }
    let hour = Math.floor((time / 60 / 60) % 24)
    if (duration.length || hour > 0) {
      duration.push(hour)
    }
    let minute = Math.floor((time / 60) % 60)
    if (duration.length || minute > 0) {
      duration.push(minute < 10 ? '0' + minute : minute)
    }
    let second = Math.floor(time % 60)
    if (duration.length || second > 0) {
      duration.push(second < 10 ? '0' + second : second)
    }
  }
  return duration
}

export function randomString (length) {
  let text = ''
  const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

  for (let i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length))
  }

  return text
}

export function getTimestamp () {
  const date = new Date()
  const timeString = Date.parse(date).toString()
  return timeString.slice(0, timeString.length - 3)
}
